package com.example.cardgame

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import android.util.Base64

// Define constants
const val NAME = "name"
const val STU_NUMBER = "stuNumber"
const val PHONE_NUMBER = "phoneNumber"
const val EMAIL = "email"
const val GENDER = "gender"
const val HOBBY = "hobby"
const val AVATAR = "avatar"
const val BEST_SCORE = "bestScore"

class Home : AppCompatActivity() {
    // 定义请求码
    companion object {
        const val REQUEST_CODE_UPDATE = 1
        const val REQUEST_CODE_GAME = 2
    }

    // 初始化个人信息的默认值
    private var my_name = "杨雪琴"
    private var my_gender = "女"
    private var my_stuNumber = "2022110650"
    private var my_phoneNumber = "1234567890"
    private var my_email = "2022110650@sicnu.edu.cn"
    private var my_hobby = "阅读"
    private var my_avatar = R.drawable.avatar
    private var my_bestScore = 0
    private var encodedImage: String? = null

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_home)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //获取控件
        val name: TextView = findViewById(R.id.name)
        val gender: TextView = findViewById(R.id.gender)
        val stuNumber: TextView = findViewById(R.id.stuNumber)
        val phoneNumber: TextView = findViewById(R.id.phoneNumber)
        val email: TextView = findViewById(R.id.email)
        val hobby: TextView = findViewById(R.id.hobby)
        val avatar: ImageView = findViewById(R.id.avatar)
        val bestScore: TextView = findViewById(R.id.bestScore)

        //更新个人信息视图
        updatePersonalInfoViews(name, gender, stuNumber, phoneNumber, email, hobby, avatar, bestScore)

        //更新按钮点击事件
        val updateButton: Button = findViewById(R.id.update)
        updateButton.setOnClickListener {
            val intent = Intent(this, PersonInfomation::class.java)
            // Pass current personal information to PersonInfomation
            intent.putExtra(NAME, my_name)
            intent.putExtra(STU_NUMBER, my_stuNumber)
            intent.putExtra(PHONE_NUMBER, my_phoneNumber)
            intent.putExtra(EMAIL, my_email)
            intent.putExtra(GENDER, my_gender)
            intent.putExtra(AVATAR, my_avatar)
            intent.putExtra(HOBBY, my_hobby)
            intent.putExtra("image", encodedImage)
            startActivityForResult(intent, REQUEST_CODE_UPDATE)
        }

        //开始游戏按钮点击事件
        val gameButton: Button = findViewById(R.id.startGame)
        gameButton.setOnClickListener {
            val intent = Intent(this, CardGame::class.java)
            // Pass best score to CardGame
            intent.putExtra(BEST_SCORE, my_bestScore)
            startActivityForResult(intent, REQUEST_CODE_GAME)
        }
    }

    //更新个人信息视图
    private fun updatePersonalInfoViews(//参数为个人信息视图控件
        name: TextView, gender: TextView, stuNumber: TextView, phoneNumber: TextView,
        email: TextView, hobby: TextView, avatar: ImageView, bestScore: TextView
    ) {
        name.text = String.format("%s：%s", getString(R.string.name), my_name)
        gender.text = String.format("%s：%s", getString(R.string.gender), my_gender)
        stuNumber.text = String.format("%s：%s", getString(R.string.stuNumber), my_stuNumber)
        phoneNumber.text = String.format("%s：%s", getString(R.string.phoneNumber), my_phoneNumber)
        email.text = String.format("%s：%s", getString(R.string.email), my_email)
        hobby.text = String.format("%s：%s", getString(R.string.hobby), my_hobby)
        bestScore.text = String.format("%s：%s", getString(R.string.bestScore), my_bestScore.toString())
        if (encodedImage != null) { // 如果图像不为空，则解码并将其设置到 ImageView
            val byteArray = Base64.decode(encodedImage, Base64.DEFAULT) // 解码 Base64 编码的字符串
            val imageBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)   // 将字节数组解码为位图
            avatar.setImageBitmap(imageBitmap)// 将位图设置到 ImageView
        } else {
            avatar.setImageResource(my_avatar)  // 否则设置默认头像
        }
    }

    //处理返回的数据
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_UPDATE && resultCode == Activity.RESULT_OK) {
            data?.let {
                //接收传递过来的个人信息
                my_name = it.getStringExtra(NAME) ?: my_name
                my_stuNumber = it.getStringExtra(STU_NUMBER) ?: my_stuNumber
                my_phoneNumber = it.getStringExtra(PHONE_NUMBER) ?: my_phoneNumber
                my_email = it.getStringExtra(EMAIL) ?: my_email
                my_gender = it.getStringExtra(GENDER) ?: my_gender
                my_hobby = it.getStringExtra(HOBBY) ?: my_hobby
                encodedImage = it.getStringExtra("image")

                //更新个人信息视图
                updatePersonalInfoViews(
                    findViewById(R.id.name), findViewById(R.id.gender), findViewById(R.id.stuNumber),
                    findViewById(R.id.phoneNumber), findViewById(R.id.email), findViewById(R.id.hobby),
                    findViewById(R.id.avatar), findViewById(R.id.bestScore)
                )
            }
        } else if (requestCode == REQUEST_CODE_GAME && resultCode == Activity.RESULT_OK) {
            data?.let {
                my_bestScore = it.getIntExtra("bestScore", my_bestScore)    //接收传递过来的最高分
                findViewById<TextView>(R.id.bestScore).text = String.format("%s：%s", getString(R.string.bestScore), my_bestScore.toString())
            }
        }
    }
}